package org.feng.common;

import lombok.extern.slf4j.Slf4j;
import org.feng.common.util.ExecuteExpressUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求响应拦截器
 *
 * @author fengjinsong
 */
@Slf4j
public class RequestHolderInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestHolder.REQUEST_LOCAL.set(request);
        RequestHolder.RESPONSE_LOCAL.set(response);

        // 设置用户信息，从请求头中获取
        setUserInfo(request);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }

    /**
     * 请求头中的参数获取，并设置到用户信息本地线程中
     */
    private void setUserInfo(HttpServletRequest request) {

        // TODO 后序改造为签名方式--
        // 角色ID
        String roleId = request.getHeader("roleId");
        // 用户名
        String username = request.getHeader("username");
        // 用户ID
        String userId = request.getHeader("userId");

        RequestHeaderUserInfo userInfo = new RequestHeaderUserInfo();
        ExecuteExpressUtil.setIfPresent(StringUtils.hasLength(username), () -> userInfo.setUsername(username));
        ExecuteExpressUtil.setIfPresent(StringUtils.hasLength(userId), () -> userInfo.setUserId(Integer.parseInt(userId)));
        ExecuteExpressUtil.setIfPresent(StringUtils.hasLength(roleId), () -> userInfo.setRoleId(Integer.parseInt(roleId)));

        RequestHolder.REQUEST_HEADER_USER_INFO_THREAD_LOCAL.set(userInfo);
    }
}
